package com.ray.service;

import static org.hamcrest.CoreMatchers.nullValue;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.GradeBean;
import com.ray.bean.WorkOrderBean;
import com.ray.bean.WorkOrderMachineBean;
import com.ray.bean.WorkOrderMaterialPriceDetail;
import com.ray.exception.ServiceException;
import com.ray.mapper.WorkOrderMapper;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.redis.RedisCache;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

@Service
public class WorkOrderService {

	
	@Autowired
	WorkOrderMapper workOrderMapper;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	InternetThingCardService internetThingCardService;
	/**
	 * 获取工单维修配置列表
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean getConfigList(Map map,WorkOrderMachineBean workOrderMachineBean) {
		// TODO Auto-generated method stub
		DatatablesViewPageBean bean = new DatatablesViewPageBean();
		
		List<WorkOrderMachineBean> lists = workOrderMapper.getConfigList(map,workOrderMachineBean);
		
		for(WorkOrderMachineBean listBean : lists) {
			String serviceWorker = listBean.getServiceWorker(); 
			String serviceWorkerStr="";
			for(int i=0;i<serviceWorker.split(",").length;i++) {
				if(workOrderMapper.checkUserIsUse(map.get("loginCompany").toString(),serviceWorker.split(",")[i])>0) {
					serviceWorkerStr+=serviceWorker.split(",")[i]+",";
				}
			}
			if(serviceWorkerStr.length()>0) {
				listBean.setServiceWorker(serviceWorkerStr.substring(0,serviceWorkerStr.length()-1));
			}else {
				listBean.setServiceWorker("");
			}

			
		}
		
		bean.setReturnData(lists);
		int total = workOrderMapper.getConfigListTotal(map,workOrderMachineBean);
		bean.setiTotalDisplayRecords(total);
		bean.setiTotalRecords(total);
		return bean;
	}
	/**
	 * 获取工单维修配置信息通过id
	 * @param map
	 * @return
	 */
	public WorkOrderMachineBean getConfigById(Map map, WorkOrderMachineBean bean) {
		// TODO Auto-generated method stub
		WorkOrderMachineBean workOrderMachineBean = workOrderMapper.getConfigById(map,bean);
		String serviceWorker = workOrderMachineBean.getServiceWorker();
		String serviceWorkerStr="";
		if(map!=null&&serviceWorker.indexOf(",")>-1&&workOrderMachineBean.getCompany().equals(map.get("loginCompany").toString())) {
			for(int i=0;i<serviceWorker.split(",").length;i++) {
				if(workOrderMapper.checkUserIsUse(map.get("loginCompany").toString(),serviceWorker.split(",")[i])>0) {
					serviceWorkerStr+=serviceWorker.split(",")[i]+",";
				}
			}
			workOrderMachineBean.setServiceWorker(serviceWorkerStr.substring(0,serviceWorkerStr.length()-1));
		}
		return workOrderMachineBean;
	}
	/**
	 * 更新工单维修配置
	 * @param map
	 * @param bean
	 * @return
	 */
	public int updateConfig(Map map, WorkOrderMachineBean bean) {
		// TODO Auto-generated method stub
		//校验internet_things_card是否存在
		if(map.get("internetThingsCard")!=""&&internetThingCardService.checkCardIsRepeat(map)) {//不存在
			throw new ServiceException("物料网卡编号【"+map.get("internetThingsCard")+"】系统不存在");
		}
		//internet_things_card唯一
		List<WorkOrderMachineBean> beans = workOrderMapper.getWorkOrderMachineByInternetThingsCard(bean.getId(),bean.getInternetThingsCard());
		if(beans.size()>0) {//不存在
			throw new ServiceException("物料网卡编号【"+map.get("internetThingsCard")+"】已使用不能重复绑定");
		}
		if("".equals(bean.getInternetThingsCard())) {
			bean.setInternetThingsCard(null);
		}
		return workOrderMapper.updateConfig(map,bean);
	}
	/**
	 * 增加工单维修配置
	 * @param map
	 * @param bean
	 * @return
	 */
	public WorkOrderMachineBean addConfig(Map map, WorkOrderMachineBean bean) {
		// TODO Auto-generated method stub
		if(map.get("internetThingsCard")!=""&&internetThingCardService.checkCardIsRepeat(map)) {//不存在
			throw new ServiceException("物料网卡编号【"+map.get("internetThingsCard")+"】系统不存在");
		}
		//internet_things_card唯一
		List<WorkOrderMachineBean> beans = workOrderMapper.getWorkOrderMachineByInternetThingsCard(bean.getId(),bean.getInternetThingsCard());
		if(beans.size()>0) {//不存在
			throw new ServiceException("物料网卡编号【"+map.get("internetThingsCard")+"】已使用不能重复绑定");
		}
		if("".equals(bean.getInternetThingsCard())) {
			bean.setInternetThingsCard(null);
		}
		workOrderMapper.addConfig(map,bean);
		return bean;
	}
	/**
	 * 设备工单申请 发送模版消息到主管
	 * @throws ServiceException 
	 */
	public void addApplyWorkOrder(Map map, WorkOrderBean bean) throws ServiceException {
		// TODO Auto-generated method stub
		if(bean.getMachineId()==0) {
			throw new ServiceException("参数machineId不存在");
		}
		//避免重复申请 同一个机器型号只能申请一次 并且在维修之后这个工单算结束 
		//直接调用接口
		WorkOrderBean workOrderBean = this.getApplyWorkOrderByMachineId(map,bean);
		if(workOrderBean.getId()>1) {
			throw new ServiceException("该设备已经申请维修,请勿重复申请");
		}
		WorkOrderMachineBean machineBean = new WorkOrderMachineBean();
		machineBean.setId(bean.getMachineId());
		WorkOrderMachineBean machineBeanInfo = this.getConfigById(map, machineBean);
		bean.setCustCompany(machineBeanInfo.getBuyer());
		bean.setWorkCompany(machineBeanInfo.getCompany());
		//获取系统错误信息
		if(machineBeanInfo.getInternetThingsCard()!=null&&!"".equals(machineBeanInfo.getInternetThingsCard())) {
			Map<String, Object> errorMap = workOrderMapper.getAlarmCodeAndMsg(machineBeanInfo.getInternetThingsCard());
			if(errorMap!=null) {
				bean.setErrorCode(errorMap.get("errorCode").toString());
				bean.setErrorMsg(errorMap.get("errorMsg").toString());
			}
		}
		//保存申请单
		workOrderMapper.saveWorkOrderApply(map,bean);
		//写入到redis
		RedisCache.setDataToRedis(machineBeanInfo.getCompany()+"/workOrder/addApplyWorkOrder", bean, "");
		//发送模版给模版消息主管
		if(bean.getId()>0) {
			sendTemplateInfoForWorkManager(map,bean);
		}
	}
	/**
	 * 通过设备id获取工单
	 * @param map
	 * @param bean
	 * @return
	 */
	public WorkOrderBean getApplyWorkOrderByMachineId(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		return workOrderMapper.getApplyWorkOrderByMachineId(map,bean);
	}
	/**
	 * 通过工单id获取工单
	 * @param map
	 * @param bean
	 * @return
	 */
	public WorkOrderBean getApplyWorkOrderById(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		return workOrderMapper.getApplyWorkOrderById(map,bean);
	}
	/**
	 * 更新工单指派人
	 * @param map
	 * @param bean
	 * @return
	 */
	public int updateWorkOrderWorkName(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		int total = workOrderMapper.updateWorkOrderWorkName(map,bean);
		sendTemplateInfoForWorkManagerToWork(map, bean);
		return total;
	}
	/**
	 * 二次修改指派人
	 * @param map
	 * @param bean
	 * @return
	 */
	public int updateWorkOrderWorkNameTwice(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		int total = workOrderMapper.updateWorkOrderWorkNameTwice(map,bean);
		sendTemplateInfoForWorkManagerToWork(map, bean);
		return total;
	}
	/**
	 * 维修技工完善修改信息
	 * @param map
	 * @param bean
	 * @return
	 */
	public int updateWorkOrderWorkRepaireInfo(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		int total = workOrderMapper.updateWorkOrderWorkRepaireInfo(map,bean);
		sendTemplateInfoForApplyManRepaireInfo(map, bean);
		return total;
	}
	/**
	 * 更新用户评价
	 * @param map
	 * @param bean
	 * @return
	 */
	public int updateWorkOrderCustEvaluation(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		int total = workOrderMapper.updateWorkOrderCustEvaluation(map,bean);
		sendTemplateInfoForCustEvaluation(map, bean);
		return total;
	}
	
	
	
	/**
	 * 
	 * @param map
	 * @return
	 */
	public List<Map> getCompanyUserTree(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.getCompanyUserTree(map);
	}
	/**
	 * 获取订单
	 * @param map
	 * @return
	 */
	public List<Map> getOrderTree(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.getOrderTree(map);
	}
	/**
	 * 更新申请工单状态
	 * @param map
	 * @param bean
	 * @return
	 */
	public int updateApplyOrderStatus(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		return workOrderMapper.updateApplyOrderStatus(map,bean);
	}
	/**
	 * 更新用户补充说明
	 * @param map
	 * @param bean
	 * @return
	 */
	public int updateApplyOrderRemark(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		return workOrderMapper.updateApplyOrderRemark(map,bean);
	}
	/**
	 * 申请工单列表
	 * @param map
	 * @param bean
	 * @return
	 */
	public DatatablesViewPageBean getApplyList(Map map) {
		// TODO Auto-generated method stub
		DatatablesViewPageBean bean = new DatatablesViewPageBean();
		bean.setReturnData(workOrderMapper.getApplyList(map));
		int total = workOrderMapper.getApplyListTotal(map);
		bean.setiTotalDisplayRecords(total);
		bean.setiTotalRecords(total);
		return bean;
	}
	/**
	 * 通过用户名 公司 或则用户id 公司获取用户id
	 */
	public List<Map<String, String>> getOpenId(String userName,String userId,Map map) {
		return workOrderMapper.getOpenId(userName,userId,map);
	}
	
	/**
	 * 通过用户名 公司 或则用户id 公司获取用户id
	 */
	public Map getUserInfo(Map map) {
		return workOrderMapper.getUserInfo(map);
	}
	
	/**
	 * 更新客户评价 维修完毕1天内评论
	 */
	public void updateWorkOrderForOpinion() {
		// TODO Auto-generated method stub
		workOrderMapper.updateWorkOrderForOpinion();
	}
	
	/**
	 * 发送模板消息
	 * 功能：工单申请发送给维修主管
	 * @param map
	 * @param bean
	 */
	private void sendTemplateInfoForWorkManager(Map<String,String> map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		//通过设备id获取工单信息
		WorkOrderBean workOrderBean = workOrderMapper.getApplyWorkOrderByMachineId(map,bean);
		//获取技工主管
		String service_manager=workOrderBean.getWorkManagerName();
		//获取openId //通过用户id或则用户名称加上公司
		map.put("queryCompany", workOrderBean.getWorkCompany());
		List<Map<String, String>> openidMap = workOrderMapper.getOpenId(service_manager, "", map);
		if(openidMap!=null) {
			for(int i=0;i<openidMap.size();i++) {
				if(openidMap.get(i)==null) {
					continue;
				}
				Map<String, String> userMap = workOrderMapper.getUserInfo(map);
				String accessToken=weiXinService.getAccessToken(null);
				JSONObject data=WeixinTemplateList.packJsonNewWorkOrderApply("您有一条新的维修单提醒", workOrderBean.getMachineModel()+"设备维修", workOrderBean.getCustCompany(), (null!=userMap?userMap.get("deptName"):""), map.get("loginUserName"),(map.get("loginUserPhone").trim().length()>0?map.get("loginUserPhone"):workOrderBean.getCustPhone()), "请尽快维修，点击查看详情", null, null, null, null,  null,null,null);
				WeixinTemplateSender.sendWechatmsgToUser(openidMap.get(i).get("openid"), "h3Met0evJPqfiqrAZI0K4GOuV_lGdmWKD63ykvhetKg",  WeiXinParamesUtil.messageLink+"?loginToken="+openidMap.get(i).get("openid")+"&pageType="+RedirectUrlUtil.scanWorkOrderController+"#applyId="+bean.getId(), data, accessToken);
			}
		}
	}
	/**
	 * 发送模板消息
	 * 功能：维修主管指派工单给技工
	 * @param map
	 * @param bean
	 */
	private void sendTemplateInfoForWorkManagerToWork(Map<String,String> map, WorkOrderBean bean) {
		//通过设备id获取工单信息
		WorkOrderBean workOrderBean = workOrderMapper.getApplyWorkOrderById(map,bean);
		//获取技工名字
		String workName=bean.getWorkName();
		//获取openId //通过用户id或则用户名称加上公司
		map.put("queryCompany", workOrderBean.getWorkCompany());
		List<Map<String, String>> openidMap = workOrderMapper.getOpenId(workName, "", map);
		if(openidMap!=null) {
			for(int i=0;i<openidMap.size();i++) {
				if(openidMap.get(i)==null) {
					continue;
				}
				String accessToken=weiXinService.getAccessToken(null);
				JSONObject data=WeixinTemplateList.packJsonNewWorkOrderRecive(map.get("loginUserName")+"向您指派一个维修单", workOrderBean.getId()+"", "设备维修", workOrderBean.getCustCompany(), workOrderBean.getCustName(),workOrderBean.getCustPhone(), "请尽快维修，点击查看详情", null, null, null, null,  null,null,null);
				WeixinTemplateSender.sendWechatmsgToUser(openidMap.get(i).get("openid"), "1Nw34qFJxwxvt81l-S8H9EEzuxXo9y_rU8RP1Jvqemw", WeiXinParamesUtil.messageLink+"?loginToken="+openidMap.get(i).get("openid")+"&pageType="+RedirectUrlUtil.scanWorkOrderController+"#applyId="+bean.getId(), data, accessToken);

			}
		}
	}
	
	/**
	 * 维修技工维修完毕填写信息发送给工单申请人
	 * @param map
	 * @param bean
	 */
	private void sendTemplateInfoForApplyManRepaireInfo(Map<String,String> map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		//通过设备id获取工单信息
		WorkOrderBean workOrderBean = workOrderMapper.getApplyWorkOrderById(map,bean);
		//获取工单申请人名字
		//String custName=workOrderBean.getCustName();
		//获取openId //通过用户id或则用户名称加上公司
		//map.put("queryCompany", workOrderBean.getCustCompany());
		//Map<String, String> openidMap = workOrderMapper.getOpenId(custName, "", map);
		if(workOrderBean.getCustOpenId()!=null||!"".equals(workOrderBean.getCustOpenId())) {
			String accessToken=weiXinService.getAccessToken(null);
			JSONObject data=WeixinTemplateList.packJsonNewWorkOrderProgress("售后服务工单提醒", workOrderBean.getId()+"", workOrderBean.getMachineModel()+"-"+workOrderBean.getMachineSerialNo(), workOrderBean.getCustBrokenDescription(), "维修处理完毕", "感谢您对我们的支持,请点击评价", null, null, null, null, null, null);
			WeixinTemplateSender.sendWechatmsgToUser(workOrderBean.getCustOpenId(), "06u5Ujw3StMpifDEGmzqBxrE7tQaqgTzcCWZQ0RmZEo", WeiXinParamesUtil.YUMIN+"/weixin/workOrder/sqr?id="+workOrderBean.getMachineId(), data, accessToken);
		}
	}
	/**
	 * 用户评价工单发送给技工和主管
	 * @param map
	 * @param bean
	 */
	private void sendTemplateInfoForCustEvaluation(Map<String,String> map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
	}
	/**
	 * 获取报价明细
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean getMaterialPriceList(Map map) {
		// TODO Auto-generated method stub
		DatatablesViewPageBean bean = new DatatablesViewPageBean();
		bean.setReturnData(workOrderMapper.getMaterialPriceList(map));
		int total = workOrderMapper.getMaterialPriceListTotal(map);
		bean.setiTotalDisplayRecords(total);
		bean.setiTotalRecords(total);
		return bean;
	}
	/**
	 * 维修报价修改
	 * @param map
	 */
	public void updateMaterialPrice(Map map) {
		// TODO Auto-generated method stub
		workOrderMapper.updateMaterialPrice(map);
	}
	/**
	 * 通过关联订单编号获取物料价目
	 * @param request
	 * @param bean
	 * @return
	 */
	public List<Map> getMaterialPriceByOrderNo(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.getMaterialPriceByOrderNo(map);
	}
	/**
	 * 维修报价明细增加
	 * @param map 
	 * @param bean
	 * @return
	 */
	public WorkOrderMaterialPriceDetail addWorkRepairPrice(Map map, WorkOrderMaterialPriceDetail bean) {
		// TODO Auto-generated method stub
		bean.setCompany(map.get("loginCompany").toString());
		bean.setCreater(map.get("loginUserName").toString());
		bean.setCreaterId(map.get("loginUserId").toString());
		bean.setStatus(1);
		workOrderMapper.addWorkRepairPrice(bean);
		return bean;
	}
	/**
	 * 维修报价明细删除
	 * @param map 
	 * @param bean
	 * @return
	 */
	public int updateWorkRepairPriceById(WorkOrderMaterialPriceDetail bean) {
		// TODO Auto-generated method stub
		return workOrderMapper.updateWorkRepairPriceById(bean);
	}
	/**
	 * 获取维修报价明细清单
	 * @param map 
	 * @param bean
	 * @return
	 */
	public List<WorkOrderMaterialPriceDetail> getWorkRepairPriceList(Map map, WorkOrderMaterialPriceDetail bean) {
		// TODO Auto-generated method stub
		bean.setCompany(map.get("loginCompany").toString());
		return workOrderMapper.getWorkRepairPriceList(bean);
	}
	/**
	 * 更新结算价格
	 * @param id
	 * @param balancePrice
	 */
	public void updateBalancePrice(String id, String balancePrice) {
		// TODO Auto-generated method stub
		if(id.split(",").length==balancePrice.split(",").length) {
			for(int i=0;i<id.split(",").length;i++) {
				workOrderMapper.updateBalancePrice(id.split(",")[i],balancePrice.split(",")[i]);
			}
		}
	}
	
	/**
	 * 获取设备维修汇总看板所需数据
	 * @author nate 
	 * @param request
	 * @return
	 */
	public Map getWorkRepairSummary(Map map) {
		List<GradeBean> list=workOrderMapper.getWorkRepairSummary(map);
		Map<String , List<GradeBean>> returnMap=list.stream().collect(Collectors.groupingBy(GradeBean::getType));
		return returnMap;
	}
	
	/**
	 * 获取设备维修汇总看板所需数据
	 * @author nate 
	 * @param request
	 * @return
	 */
	public Map getWorkAlarmSummary(Map map) {
		List<GradeBean> list=workOrderMapper.getWorkAlarmSummary(map);
		Map<String , List<GradeBean>> returnMap=list.stream().collect(Collectors.groupingBy(GradeBean::getType));
		return returnMap;
	}
	
	
	/**
	 * 根据物联网卡编号获取维修设备id
	 * @param internetThingsCard
	 * @return
	 */
	public String getIdByInternetThingsCard(String internetThingsCard) {
		return workOrderMapper.getIdByInternetThingsCard(internetThingsCard);
	}
	/**
	 * 
	 * @param map
	 * @return
	 */
	public List<String> getEquimentAlarmTypeName(Map map) {
		return workOrderMapper.getEquimentAlarmTypeName(map);
	}
	/**
	 * 批量修改设备维修主管和技工
	 */
	public void updateWorkMachineManagerAndWorksBatch(Map map) {
		// TODO Auto-generated method stub
		workOrderMapper.updateWorkMachineManagerAndWorksBatch(map);
	}
	/**
	 * 获取每个月维修数据
	 * @param request
	 * @return
	 */
	public List<Map> getWorkOrderApplyDataEveryMonth(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.getWorkOrderApplyDataEveryMonth(map);
	}
	
	public List<Map> getDistrict(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.getDistrict(map);
	}
	public int insertOrUpdateWorkOrderSalaryType(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.insertOrUpdateWorkOrderSalaryType(map);
	}
	public int insertOrUpdateWorkOrderStarType(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.insertOrUpdateWorkOrderStarType(map);
	}
	public int insertOrUpdateWorkOrderVisitType(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.insertOrUpdateWorkOrderVisitType(map);
	}
	public List<Map> getBasicInfoForSalary(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.getBasicInfoForSalary(map);
	}
	public List<Map> getBasicInfoForSalaryList(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.getBasicInfoForSalaryList(map);
	}
	public int getBasicInfoForSalaryCount(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.getBasicInfoForSalaryCount(map);
	}
	public void updateWorkOrderApplyForVisit(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		workOrderMapper.updateWorkOrderApplyForVisit(map,bean);
		if(map.get("salaryType")!=null) {
			List<Map> list  =  workOrderMapper.getBasicInfoForSalary(map);
			for(Map resMap : list) {
				String actualSalary = resMap.get("actualSalary").toString();
				map.put("actualSalary", actualSalary);
				workOrderMapper.updateWorkOrderApplyForActualSalary(map,bean);
				break;
			}
		}
	}
	
	public void updateWorkOrderApplyForSalary(Map map, WorkOrderBean bean) {
		// TODO Auto-generated method stub
		List<Map> list  =  workOrderMapper.getBasicInfoForSalary(map);
		for(Map resMap : list) {
			String actualSalary = resMap.get("actualSalary").toString();
			map.put("actualSalary", actualSalary);
			workOrderMapper.updateWorkOrderApplyForActualSalary(map,bean);
			break;
		}
	}
	/**
	 * 获取在职维修人员列表
	 * @param request
	 * @return
	 */
	public List<Map> getServiceWorkerList(Map map) {
		// TODO Auto-generated method stub
		return workOrderMapper.getServiceWorkerList(map);
	}
	public void saveWorkOrderInfoForCustmerOperate(Map map) {
		workOrderMapper.saveWorkOrderInfoForCustmerOperate(map);
	}
	public Object getWorkOrderInfoForCustmerOperate(Map map) {
		DatatablesViewPageBean bean = new DatatablesViewPageBean();
		bean.setReturnData(workOrderMapper.getWorkOrderInfoForCustmerOperate(map));
		int total = workOrderMapper.getWorkOrderInfoForCustmerOperateTotal(map);
		bean.setiTotalDisplayRecords(total);
		bean.setiTotalRecords(total);
		return bean;
	}
	
}
